const _ = require('lodash');

function conquerIsland(see) {

    const get = (x, y) => ((see[x] || [])[y] || 'x');
    const dist = ([x, y]) => Math.min(...[...data.p].map(([a, b]) => Math.abs(a - x) + Math.abs(b - y)));
    const nSharks = c => data[c].s;
    const nTreasures = c => -data[c].t;
    const cost = c => '' + [nSharks, dist, nTreasures].map(f => f(c));

    let data = { u: [], m: [], p: [] };
    see.forEach((r, x) => r.forEach((c, y) => {
        if ('upm'.includes(c)) {
            let coords = [x, y];
            data[c].push(coords)
            data[coords] = [[x + 1, y], [x - 1, y], [x, y + 1], [x, y - 1]].reduce((o, [a, b]) => (o[get(a, b)] = o[get(a, b)] + 1 || 1, o), { s: 0, t: 0 });
        }
    }));
    let cnds = data.u.length ? data.u : data.m;
    if (!cnds.length) return [];

    cnds = _.sortBy(cnds, nSharks, dist, nTreasures);
    let m = cost(cnds[0]);
    let i = cnds.findIndex(c => m != cost(c));
    if (i + 1) cnds = cnds.slice(0, i);
    return cnds;
}